package cool.taomu.toolkit.core.classloader

import com.google.common.base.Optional
import java.net.JarURLConnection
import java.net.URL
import java.net.URLClassLoader
import java.util.Vector
import org.slf4j.LoggerFactory

@Deprecated
class TaomuPluginClassloader extends URLClassLoader {
	var static LOG = LoggerFactory.getLogger(TaomuPluginClassloader);
	Vector<JarURLConnection> cacheJarFiles = new Vector<JarURLConnection>();
	Class<?> zlass;

	new() {
		super(newArrayOfSize(0), findParentClassLoader());
	}

	def static findParentClassLoader() {
		var parent = Optional.of(TaomuPluginManager.classLoader);
		if (!parent.present) {
			parent = Optional.of(TaomuPluginClassloader.classLoader);
		}
		if (!parent.present) {
			parent = Optional.of(ClassLoader.systemClassLoader);
		}
		parent.get();
	}

	def loadFile(Class<?> zlass) {
		this.zlass = zlass;
	}

	override Class<?> findClass(String name) throws ClassNotFoundException {
		if (this.zlass !== null) {
			return this.zlass;
		}
		return super.findClass(name);
	}

	def loadFile(URL file) {
		var url = file.openConnection
		if (url instanceof JarURLConnection) {
			url.useCaches = true;
			this.cacheJarFiles.add(url);
		}
		addURL(file);
	}

	def unloadFile() {
		LOG.info("卸载jar 文件:{}", this.cacheJarFiles.size)
		this.cacheJarFiles.filterNull.forEach [
			it.jarFile.close;
		]
		if (this.zlass !== null) {
			this.zlass = null;
		}
	}
}
